﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TmU220PrintHelperV2d0.Entity;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.Singleton
{
    /// <summary>
    /// api接口路由
    /// </summary>
    public class RouterPhpSingletonV1d0
    {
        private static RouterPhpSingletonV1d0 _instance = null;
        private ThinkPhpApiV1d0 _phpApi = null;
        private static readonly object syslock = new object();
        /// <summary>
        /// 单例模式
        /// </summary>
        public static RouterPhpSingletonV1d0 Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (syslock)
                    {
                        if (_instance == null)
                        {
                            _instance = new RouterPhpSingletonV1d0();
                        }
                    }
                }
                return _instance;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        private RouterPhpSingletonV1d0()
        {
            _phpApi = new ThinkPhpApiV1d0();
            LoadData();
        }
        /// <summary>
        /// 装载数据
        /// </summary>
        private void LoadData()
        {
            ReloadData();
        }
        /// <summary>
        /// 从配置文件中，读取组内的接口
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="apiName"></param>
        public void ReloadData(string groupName = "TaskApi", string apiName = "routerPhp")
        {
            _phpApi = PhpApiSetSingletonV1d0.Instance.GetApi(groupName, apiName);
        }
        public string Run(string methodName,string methodParamString)
        {
            string resultOfJson = "";
            try
            {
                //接口url
                string url = _phpApi.main_url + _phpApi.method_name;
                string methodContent = ApiRouterMethodSetSingletonV1d0.Instance.GetApiRouterMethod(methodName).MethodContent;
                string paramString = string.Format("url={0}&method={1}&{2}", url,methodContent, methodParamString);
                //string paramString = string.Format("url={0}&method={1}&data={2}", url,"post", dataString);

                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        resultOfJson = rootDynamicObject.data.list.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultOfJson;
        }
        public string GetDataBySql(string sqlString)
        {
            string resultOfJson = "";
            try
            {
                //接口url
                string url = _phpApi.main_url + _phpApi.method_name;
                string methodName = "getdatabysql";

                string methodContent = ApiRouterMethodSetSingletonV1d0.Instance.GetApiRouterMethod(methodName).MethodContent;
                string paramString = string.Format("url={0}&method={1}&sql={2}", url, methodContent, sqlString);

                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        resultOfJson = rootDynamicObject.data.list.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultOfJson;
        }
        public string SetData<T>(T data)
        {
            string result = "";
            try
            {
                //接口url
                string url = _phpApi.main_url + _phpApi.method_name;
                string methodName = "setdata_net";
                string methodContent = ApiRouterMethodSetSingletonV1d0.Instance.GetApiRouterMethod(methodName).MethodContent;

                string tableName = typeof(T).Name;                
                string jsonStringOfData = JsonConvert.SerializeObject(data);
                //动态类型
                dynamic dataDynamic = data;
                int uid = dataDynamic.uid;
                string methodParamString = string.Format("tablename={0}&uid={1}&data={2}", tableName, uid, jsonStringOfData);
                string paramString = string.Format("url={0}&method={1}&{2}", url, methodContent, methodParamString);
                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        result = rootDynamicObject.uid.Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 更新或者新增主表一条记录，以及该主表对应单个子表的多条记录
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="masterData"></param>
        /// <param name="slaveDataList"></param>
        /// <returns></returns>
        public string SetDataMasterSlave<T1, T2>(T1 masterData, List<T2> slaveDataList)
        {
            string result = "";
            try
            {
                //接口url,方法内容
                string url = _phpApi.main_url + _phpApi.method_name;
                string methodName = "setdata_master_slave_net";
                string methodContent = ApiRouterMethodSetSingletonV1d0.Instance.GetApiRouterMethod(methodName).MethodContent;

                //根据类，得到类名称，内部约定类名称就是对应数据表的表名
                string masterTableName = typeof(T1).Name;
                string slaveTableName = typeof(T2).Name;
                string jsonStringOfMasterData = JsonConvert.SerializeObject(masterData);
                string jsonStringOfSlaveDatas = JsonConvert.SerializeObject(slaveDataList);
                //动态类型
                dynamic dataDynamic = masterData;
                int uid = dataDynamic.uid;
                //方法的参数字符串
                string methodParamString = string.Format("tablename={0}&uid={1}&data={2}&sub_tablename={3}" +
                                                        "&sub_data1={4}&parent_key={5}&where=parent_id={6}",
                        masterTableName, uid, jsonStringOfMasterData, slaveTableName,
                        jsonStringOfSlaveDatas, "parent_id", uid);
                string paramString = string.Format("url={0}&method={1}&{2}", url, methodContent, methodParamString);
                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        result = rootDynamicObject.uid.Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }

    }
    public class ParamOfRouterPhp
    {
        public string sql { get; set; }
        public string method { get; set; }
        public bool is_app { get; set; }
        public ParamOfRouterPhp(string sqlString,string methodString,bool isApp)
        {
            sql = sqlString;
            method = methodString;
            is_app = isApp;
        }
    }
}
